package com.hup.utils.swing.frame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

/**
 * 使用隐藏的dialog实现失去焦点后隐藏托盘菜单
 */
public class AutoHideMenu extends JPopupMenu implements FocusListener {
    private JDialog dialog;

    public AutoHideMenu() {
        this("菜单", null);
    }

    public AutoHideMenu(Image image) {
        this("菜单", image);
    }

    /**
     * @param title 如:"菜单"
     */
    public AutoHideMenu(String title) {
        this(title, null);
    }

    /**
     * @param title 如:"菜单"
     */
    public AutoHideMenu(String title, Image image) {
        dialog = new JDialog((Frame) null, title);
        dialog.setIconImage(image);
        dialog.setUndecorated(true);
        dialog.setSize(1, 1);
        dialog.setLocation(-10, -10);
        dialog.addFocusListener(this);
    }

    @Override
    public void setVisible(boolean b) {
        //处理展示菜单时,同时展示dialog
        dialog.setVisible(b);
        super.setVisible(b);
        if (b) {
            dialog.requestFocus();
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        //dialog失去焦点时的操作:隐藏菜单
        setVisible(false);
    }

    @Override
    public void focusGained(FocusEvent e) {
        //do nothing
    }
}
